package com.example.consumer;

import com.example.action.ServiceAction;
import org.apache.dubbo.config.spring.context.annotation.EnableDubbo;
import org.apache.dubbo.rpc.RpcContext;
import org.springframework.context.annotation.*;

import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author zhouyp
 * @program tp-monitor
 * @description
 * @create 2020-07-09
 */
public class Consume {

	public static void main(String[] args) throws InterruptedException {
		AnnotationConfigApplicationContext context =
				new AnnotationConfigApplicationContext(ConsumerConfiguration.class);
		context.start();
		ServiceAction action = context.getBean(ServiceAction.class);

		final long start = System.currentTimeMillis();
		long end = System.currentTimeMillis();
		final Random random = new Random();
		ExecutorService threadPool = Executors.newFixedThreadPool(20);
		while (end - start < 60 * 1000L) {
			switch (random.nextInt(3)) {
				case 1:
					threadPool.execute(action::methodA);
					break;
				case 2:
					threadPool.execute(action::methodB);
					break;
				default:
					threadPool.execute(action::methodC);
					break;
			}
			Thread.sleep(30);
			end = System.currentTimeMillis();
		}
		System.out.println("--end consume from consumer--");
		RpcContext.getContext().setAttachment("end", Boolean.TRUE.toString());
		action.methodA();
		threadPool.shutdown();
	}

	@Configuration
	@EnableDubbo(scanBasePackages = "com.example.action")
	@PropertySource("classpath:/spring/dubbo-consumer.properties")
	@ComponentScan(value = {"com.example.action"})
	@EnableAspectJAutoProxy
	static public class ConsumerConfiguration {
	}

}
